//
//  CachedUserDecoratedProvider.m
//  iPhoneMyRailApp
//
//  Created by Christopher Anderson on 01/11/2008.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "CachedXMLReader.h"


@implementation CachedXMLReader

@synthesize cache;
@synthesize requestProvider;
@synthesize oauthAPI;

- (id) init {

	self = [super init];

	if ( self ) {
		TarPhoneAppDelegate *appDelegate =  (TarPhoneAppDelegate*)[[UIApplication sharedApplication] delegate];
		self.oauthAPI =  appDelegate.oauthAPI;
		self.cache = [[CachedURLContents alloc] init];
		self.requestProvider = [[UserDecoratedHTTPRequest alloc] init];
	}

	return self;
}

- (void) makeRequest:(NSString*)url parameters:(NSArray*)inParameters {
	NSData *dataToParse;
	if ([cache isInCache:url]) {
		dataToParse = [cache cachedValue];
	} else {
		dataToParse = [self makeOAuthControlledRequest:url parameters:inParameters];
	}
	NSLog(@"Data from the wire %@", [[NSString alloc] initWithData:dataToParse encoding:NSUTF8StringEncoding]);
	[self parseXMLData:dataToParse parseError:nil];
}

- (NSData*) makeOAuthControlledRequest:(NSString*)url parameters:(NSArray*)inParameters {
	// Should cache value
	return [oauthAPI dataForMethod:url withParameters:inParameters];
}

- (void)parseXMLData:(NSData *)data parseError:(NSError **)error {	
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [parser setDelegate:self];
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    
    [parser parse];
    
    NSError *parseError = [parser parserError];
    if (parseError && error) {
        *error = parseError;
    }
    
    [parser release];
}

- (void)dealloc {
	[cache release];
	[requestProvider release];
	[super dealloc];
}



@end
